﻿using Npgsql;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace Updater
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private string connectionString = "Host=postgres-10f8ccb3cbae.volces.com;Database=idbhost;Username=qtdev;Password=ngXFO3cl;Persist Security Info=True;Include Error Detail=true;Maximum Pool Size=800;MinPoolSize=200;CommandTimeout=300;Tcp Keepalive=true;Tcp Keepalive Interval=120;Tcp Keepalive Time=120;";

        public string GetClientVersionId()
        {
            string versionId = string.Empty;

            try
            {
                using (var conn = new NpgsqlConnection(connectionString))
                {
                    conn.Open();

                    using (var cmd = new NpgsqlCommand("SELECT \"VersionId\" FROM \"client_version\" LIMIT 1", conn))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                versionId = reader["VersionId"].ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions appropriately
                Console.WriteLine("Error fetching VersionId: " + ex.Message);
            }

            return versionId;
        }
        /// <summary>
        /// 新版本保存目录路径
        /// </summary>
        private string SaveDir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
        /// <summary>
        /// 新版本保存名字
        /// </summary>
        private string SaveName = "update.zip";

        private MainModel mainModel;


        /// <summary>
        /// 新版本下载路径
        /// </summary>
        private string NewVersionZipURL;
        /// <summary>
        /// 新版本发布页路径
        /// </summary>
        private string NewVersionURL;
        public MainWindow()
        {
            InitializeComponent();
            mainModel = new MainModel();

            DataContext = mainModel;

           
            string path = GetClientVersionId();

            SaveName = path + ".zip";
           this.NewVersionZipURL = $"\\\\172.16.10.200\\share\\实盘客户端程序\\" + path+".zip";
            //Check();
        }

        private void Check()
        {
            Download();
        }

        private async void Download()
        {
            SetStatus("正在下载新版本文件...", false);

            UpdateBtn.Visibility = Visibility.Collapsed;
            ReCheckBtn.Visibility = Visibility.Collapsed;
            ProgressBar.Visibility = Visibility.Visible;
            mainModel.ProcessValue = 0;

            var res = await Task.Run(() =>
            {
                try
                {
                    //  确认保存目录
                    if (!Directory.Exists(SaveDir))
                    {
                        Directory.CreateDirectory(SaveDir);
                    }

                    // 构造本地文件路径
                    string localFilePath = Path.Combine(SaveDir, Path.GetFileName(NewVersionZipURL));

                    // 拷贝文件
                    File.Copy(NewVersionZipURL, localFilePath, true);
                    //Uri uri = new Uri(NewVersionZipURL);
                    //HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                    //httpWebRequest.Timeout = 120 * 1000;
                    //HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();


                    //long totalBytes = httpWebResponse.ContentLength;

                    //Stream st = httpWebResponse.GetResponseStream();
                    //Stream so = new FileStream(System.IO.Path.Combine(SaveDir, SaveName), FileMode.Create);

                    //long totalDownloadedByte = 0;
                    //byte[] by = new byte[1024];
                    //int osize = st.Read(by, 0, (int)by.Length);
                    //while (osize > 0)
                    //{

                    //    totalDownloadedByte = osize + totalDownloadedByte;
                    //    so.Write(by, 0, osize);

                    //    osize = st.Read(by, 0, (int)by.Length);

                    //    //进度计算
                    //    double process = double.Parse(String.Format("{0:F}",
                    //           ((double)totalDownloadedByte / (double)totalBytes * 100)));
                    //    mainModel.ProcessValue = process;
                    //    //Debug.WriteLine(ProcessValue);
                    //}
                    //关闭资源
                    //httpWebResponse.Close();
                    //so.Close();
                    //st.Close();

                    return true;

                }
                catch (Exception ec)
                {
                    return false;
                }
            });

            if (res)
            {
                //  准备更新
                var process = Process.GetProcessesByName("PlaceOrder_Client");
                if (process != null && process.Length > 0)
                {
                    process[0].Kill();
                }

                SetStatus("下载完成，正在解压请勿关闭此窗口...");

                string unpath = AppDomain.CurrentDomain.BaseDirectory;

                var unresult = await Task.Run(async () =>
                {
                    await Task.Delay(3000);
                    return Unzip.ExtractZipFile(System.IO.Path.Combine(SaveDir, SaveName), unpath);
                });
                if (unresult)
                {
                    SetStatus("更新完成！", false);
                    //Process tai = new Process();
                    //ProcessStartInfo startInfo = new ProcessStartInfo(System.IO.Path.Combine(unpath, "Tai.exe"));
                    //tai.StartInfo = startInfo;
                    //tai.Start();
                }
                else
                {
                    SetStatus("解压文件时发生异常，请重试！通常情况可能是因为Tai主程序尚未退出。", false);
                    UpdateBtn.Visibility = Visibility.Visible;

                }
            }
            else
            {
                //下载发生异常
                SetStatus("下载时发生异常，请重试。", false);
                UpdateBtn.Visibility = Visibility.Visible;
            }
        }


        private void SetStatus(string statusText, bool isLoading = true)
        {
            StatusLabel.Text = statusText;
            ProgressBar.IsIndeterminate = isLoading;
            if (isLoading)
            {
                ProgressBar.Visibility = Visibility.Visible;
            }
            else
            {
                ProgressBar.Visibility = Visibility.Collapsed;
            }
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(new ProcessStartInfo(NewVersionURL));
        }

        private void ReCheckBtn_Click(object sender, RoutedEventArgs e)
        {
            Check();
        }

        private void UpdateBtn_Click(object sender, RoutedEventArgs e)
        {
            Download();
        }
    }
}